import React, { useEffect, useContext } from 'react';
import { Form, Divider } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import { InspectorContext } from '../FlowManage';
import { UploadFile } from 'admin/components/UploadFile';
import { verifyTansferNumber } from 'utils/tools';
import { CustomFormItemsHoc } from './CustomFormHoc';

/**
 * 转人工组件
 * 示例：AI管理-机器人管理-版本管理-配置话术流程
 */
const TransferManualServiceComponent: React.FC = () => {
  const [form] = useForm();
  const { versionId, selectedData, onInputChange, isView } = useContext(InspectorContext);

  const { Input, Switch, InputNumber, Radio, RadioGroup } = CustomFormItemsHoc({
    disabled: isView,
  });

  /**初始化值 */
  const flowTTSWaitTipsInfo_init = {
    // 提示内容
    text: undefined,
    // 音色：TTS id
    ttsId: undefined,
    // 音量
    volume: 50,
    // 语速
    speechSpeed: 0,
    // 语调
    intonation: 0,
  };

  useEffect(() => {
    if (selectedData.transferManualMode === undefined) {
      console.log(
        '%%%%%%%%%%%%%%%兼容旧版本【转人工组件】>>>>>>>>>>>transferManualMode初始值:',
        selectedData.transferManualMode
      );
      const val = selectedData.phoneNumber ? 1 : 0;
      onInputChange('transferManualMode', val, true);
    }
    // 需要手动设置form数据, initialValue初始化属性在切换同组件的props数据时不会更新
    form.setFieldsValue(selectedData);
    form.validateFields();
  }, [form, onInputChange, selectedData]);

  /**转人工方式改变 */
  const changeTransferManualMode = (value: number) => {
    onInputChange('transferManualMode', value, true);
    // 清空phoneNumber
    onInputChange('phoneNumber', '', true);
  };
  return (
    <>
      <Form layout="vertical" form={form}>
        <Form.Item
          label="转人工组件名称"
          name="title"
          rules={[
            {
              required: true,
              whitespace: true,
              max: 10,
              message: '仅支持输入10个以内字符',
            },
          ]}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input
            maxLength={10}
            // onChange={e => {
            //   onInputChange("title", e.target.value, e.type === "blur");
            // }}
            onBlur={(e: { target: { value: any }; type: string }) => {
              onInputChange('title', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        <Form.Item style={{ marginBottom: 10 }}>
          <RadioGroup
            value={selectedData.transferManualMode}
            onChange={(e: any) => changeTransferManualMode(e.target.value)}
          >
            <Radio value={0}>转给人机协同坐席</Radio>
            <Radio value={1}>转给指定号码</Radio>
          </RadioGroup>
        </Form.Item>
        {selectedData.transferManualMode === 0}
        {selectedData.transferManualMode === 1 && (
          <Form.Item
            label=""
            name="phoneNumber"
            validateFirst
            rules={verifyTansferNumber}
            getValueFromEvent={event => {
              return event.target.value.replace(/[^0-9]+/g, '').slice(0, 30);
            }}
          >
            <Input
              minLength={1}
              maxLength={30}
              placeholder="请输入手机或者座机号码"
              // onChange={e => {
              // onInputChange('phoneNumber', e.target.value, true);
              // }}
              onBlur={(e: { target: { value: any } }) => {
                onInputChange('phoneNumber', e.target.value, true);
              }}
            />
          </Form.Item>
        )}

        <Form.Item label="等待音设置">
          <Switch
            defaultChecked={selectedData.waitVoiceSwitch === 'on'}
            onChange={(status: any) => {
              onInputChange('waitVoiceSwitch', status ? 'on' : 'off', true);
              if (!status) {
                // 关闭时，需要清空
                onInputChange('voiceType', undefined, true);
                onInputChange('flowTTSWaitTipsInfo', {}, true);
                onInputChange('tipsVoiceFile', undefined, true);
                onInputChange('tipsVoiceFileRemote', undefined, true);
                onInputChange('waitVoiceFile', undefined, true);
                onInputChange('waitVoiceFileRemote', undefined, true);
                onInputChange('playDuration', undefined, true);
              } else {
                console.log('tts-2');
                // 开启时，初始化，类型默认为TTS
                onInputChange('voiceType', 0, true);
                onInputChange('flowTTSWaitTipsInfo', flowTTSWaitTipsInfo_init, true);
              }
              console.log('flowTTSWaitTipsInfo-init-1');
            }}
          />
        </Form.Item>
        {selectedData.waitVoiceSwitch === 'on' && (
          <>
            <Divider />
            <Form.Item label="等待提示" required>
              <RadioGroup
                value={selectedData.voiceType}
                onChange={(e: any) => {
                  // 需要清空上传文件
                  onInputChange('voiceType', e.target.value, true);
                  if (e.target.value === 0) {
                    onInputChange('flowTTSWaitTipsInfo', flowTTSWaitTipsInfo_init, true);
                  } else {
                    onInputChange('flowTTSWaitTipsInfo', {}, true);
                  }
                  console.log('flowTTSWaitTipsInfo-change-2');
                  onInputChange('tipsVoiceFile', undefined, true);
                  onInputChange('tipsVoiceFileRemote', undefined, true);
                }}
              >
                <Radio value={0}>TTS</Radio>
                <Radio value={1}>录音</Radio>
              </RadioGroup>
            </Form.Item>
            {selectedData.voiceType === 0 && (
              <Form.Item
                name="tipsVoiceFile"
                rules={[
                  {
                    required: true,
                    message: '请配置TTS',
                  },
                ]}
              >
                <UploadFile
                  upload={false}
                  disabled={isView}
                  mixTTS
                  key={'TTS' + selectedData.voiceType}
                  fileId={versionId}
                  initFilePath={selectedData.tipsVoiceFileRemote}
                  extraData={selectedData.flowTTSWaitTipsInfo}
                  nameStr="提示录音-TTS"
                  callback={newObj => {
                    console.log('TTS配置-回调-参数--ok', newObj);
                    // eslint-disable-next-line prefer-const
                    let { tipsInfo, fileName, filePath } = newObj;
                    if (!tipsInfo) {
                      // 删除音频文件，重置初始值
                      tipsInfo = flowTTSWaitTipsInfo_init;
                    }
                    onInputChange('flowTTSWaitTipsInfo', tipsInfo, true);
                    onInputChange('tipsVoiceFile', fileName, true);
                    onInputChange('tipsVoiceFileRemote', filePath, true);
                  }}
                />
              </Form.Item>
            )}
            {selectedData.voiceType === 1 && (
              <Form.Item
                name="tipsVoiceFile"
                rules={[
                  {
                    required: true,
                    message: '请上传提示录音',
                  },
                ]}
              >
                <UploadFile
                  record
                  disabled={isView}
                  key={'录音' + selectedData.voiceType}
                  fileId={versionId}
                  initFilePath={selectedData.tipsVoiceFileRemote}
                  nameStr="提示录音-录音"
                  callback={obj => {
                    console.log('上传成功');
                    const { fileName, filePath } = obj;
                    onInputChange('tipsVoiceFile', fileName, true);
                    onInputChange('tipsVoiceFileRemote', filePath, true);
                  }}
                />
              </Form.Item>
            )}
            <Divider />
            <Form.Item
              label="等待音乐"
              name="waitVoiceFile"
              rules={[{ required: true, message: '请上传等待音乐' }]}
            >
              {/* 上传控件 */}
              <UploadFile
                key="等待音乐"
                record={false}
                disabled={isView}
                fileId={versionId}
                initFilePath={selectedData.waitVoiceFileRemote}
                nameStr="等待音乐"
                callback={obj => {
                  console.log('上传成功');
                  const { fileName, filePath } = obj;
                  onInputChange('waitVoiceFile', fileName, true);
                  onInputChange('waitVoiceFileRemote', filePath, true);
                }}
              />
            </Form.Item>
            <Divider />
            <Form.Item label="播放时长" required>
              <Form.Item
                name="playDuration"
                rules={[{ required: true, message: '输入0-2000数字' }]}
                noStyle
              >
                <InputNumber
                  min={0}
                  max={2000}
                  precision={0}
                  placeholder="请输入音乐播放时长"
                  style={{ width: 200, marginRight: '5px' }}
                  onBlur={(e: { target: { value: any } }) => {
                    onInputChange('playDuration', Number(e.target.value), true);
                  }}
                />
              </Form.Item>
              <span>秒</span>
            </Form.Item>
          </>
        )}
      </Form>
    </>
  );
};

export default TransferManualServiceComponent;
